﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ecopsy.Tools;
using AgencyEntityLib.BaseEntity;
using System.Web.UI.WebControls;
using Ecopsy.DataTier;
using AgencyEntityLib.Context;
/// <summary>
/// Выдавать источники TreeDictionary - 
/// В контексте текущего агентсва и заданного департамента  (в соответсвии с настройками департамента)
/// </summary>
public class TreeDictionaryContext
{
    private wsDictionary _ws_Dictionary;    

    public TreeDictionaryContext()
    {
        _ws_Dictionary = (wsDictionary)AgencyLib_GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Dictionary];
    }

    #region короткие обращения к древовидным справочникам
    
    //Адресные програмы - всегда только системные
    public TreeDictionaryItem GetAdressProgramm()
    {        
        wsDictionary _ws_Dictionary = new wsDictionary(); 
        TreeDictionaryItem[] FullList = _ws_Dictionary.GetTreeDictionaryOfType(AgencyLib_GlobalConstants.TreeDictionaryFolderType_System, AgencyLib_GlobalConstants.TreeDictionary_AdressProgram);

        TreeDictionaryItem Proxy = new TreeDictionaryItem { Name = "Адресные программы", TypeID = AgencyLib_GlobalConstants.TreeDictionary_AdressProgram, ID = AgencyLib_GlobalConstants.qProxyId };
        
        foreach (TreeDictionaryItem item in FullList)
        {
            Proxy.ChildNodes.Add(item);
        }
        return Proxy;
    }


    //Адресные програмы - всегда только системные
    public TreeDictionaryItem[] GetAdressProgrammAsArray()
    {
        wsDictionary _ws_Dictionary = new wsDictionary(); 
        TreeDictionaryFolder f = _ws_Dictionary.GetTreeDictionaryFolder(AgencyLib_GlobalConstants.TreeDictionaryFolderType_System);
        TreeDictionaryItem[] r = f.ListTreeDictionaryItems.ToArray<TreeDictionaryItem>();

        var result =
            from
                n in r
            where
              n.TypeID == AgencyLib_GlobalConstants.TreeDictionary_AdressProgram
            select n;
        TreeDictionaryItem[] rr = result.ToArray<TreeDictionaryItem>();

        return rr;
    }



    /// <summary>
    /// Вернуть справочник 
    /// </summary>
    /// <param name="FolderId">Папка справочников системная/агенства</param>
    /// <param name="DictionaryID">Ид справочника</param>
    /// <returns></returns>
    public TreeDictionaryItem GetTreeDictionary(string FolderId, string DictionaryID)
    {
        wsDictionary _ws_Dictionary = new wsDictionary();
        return  (TreeDictionaryItem)_ws_Dictionary.GetTreeDictionary(FolderId,DictionaryID);

    }
    
    public TreeDictionaryItem GetConstractionType()
    {        
        // получить справочник 
        return  (TreeDictionaryItem)_ws_Dictionary.GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionaryFolderType_System, 
                                                                     AgencyLib_GlobalConstants.TreeDictionary_ConstractionType);
       
    }
        
    public TreeDictionaryItem GetConstractionCondition()
    {
        return GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionary_ConstractionConditions);           

    }

    public TreeDictionaryItem GetTransportLocation()    
    {
        return GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionary_LocationDescribe);   
    }

    public TreeDictionaryItem GetClientsCategory()
    {
        return GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionary_ClientsCategory);           
    }

    public TreeDictionaryItem GetGeoBinding()
    {
        return GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionary_GeoBinding);
    }

    public TreeDictionaryItem GetClientStatus()
    {
        return GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionary_ClientStatus);        

    }

    public TreeDictionaryItem GetTaskCategory()
    {
        return GetTreeDictionary(AgencyLib_GlobalConstants.TreeDictionary_TaskCategory);
    }
    #endregion


    /// <summary>
    /// получить id папки в зависимости от настроек карты справочника текущео агентсва
    /// </summary>
    /// <param name="TreeDictionaryId"></param>
    /// <returns></returns>
    public static string GetFolderId(string TreeDictionaryId )
    {
        bool b = AgencyLib_GlobalConstants.CurrentAgency.CheckSetting_UseSystemDictionary(TreeDictionaryId);
        if(b) return AgencyLib_GlobalConstants.TreeDictionaryFolderType_System;
        return AgencyLib_GlobalConstants.CurrentAgency.ID;
    }

    /// <summary>
    /// Получить деревянный справочник по id
    /// </summary>
    /// <param name="ID"></param>
    /// <returns></returns>
    public static TreeDictionaryItem GetTreeDictionary(string ID)
    {
        wsDictionary _ws_Dictionary = (wsDictionary)AgencyLib_GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Dictionary];
        TreeDictionaryItem[]  list=_ws_Dictionary.GetTreeDictionaryOfType(GetFolderId(ID), ID);
        if (list.Length ==1) return list[0];
        return null;
    }

    
    /// <summary>
    /// Получить деревянный справочник по типу.  (для всех, кроме адресных программ - тип и id справочника в папке тождественны)
    /// для адреса - возвращает - дерево доступных агентсву  адресных программ 
    /// </summary>
    /// <param name="Type"></param>
    /// <returns></returns>
    public TreeDictionaryItem GetТрееDictionaryItem(string Type)
    { 
        switch (Type)
            {
            case AgencyLib_GlobalConstants.TreeDictionary_ConstractionType  :
                    return GetConstractionType();
            case AgencyLib_GlobalConstants.TreeDictionary_AdressProgram :
                    return GetAdressProgramm();
            case AgencyLib_GlobalConstants.TreeDictionary_LocationDescribe  :
                    return GetTransportLocation();
            case AgencyLib_GlobalConstants.TreeDictionary_ConstractionConditions :
                    return GetConstractionCondition();
            case AgencyLib_GlobalConstants.TreeDictionary_GeoBinding:
                    return GetGeoBinding();
            case AgencyLib_GlobalConstants.TreeDictionary_ClientsCategory:
                    return GetClientsCategory();
            case AgencyLib_GlobalConstants.TreeDictionary_ClientStatus :
                    return GetClientStatus();

            }
        return null;
    }

    /// <summary>
    /// Возвращает строковое значение древовидного свойства
    /// </summary>
    /// <param name="Value"></param>
    /// <returns></returns>
    public  static string GetPropertyVal(TreeDictionaryItemValue Value)
    {
        if (null == Value) return string.Empty;
        return Value.GetValueAsString();
        //wsDictionary ws = (wsDictionary)AgencyLib_GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Dictionary];
        //TreeDictionaryItem d = ws.GetTreeDictionary(Value.TreeDictionaryFolderID, Value.ID);
        //return d.ValueAsString(Value, " ", "/");
    }
 
    
}
